<?php

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;


class FinanceWithdrawOrder extends Base
{
    protected $financeWithdrawOrderTable = 'finance_withdraw_order';
    protected $financeYuqueTable = 'finance_yuque';

    // 提现规则限制 全局设定
    protected $redisKeyWithdrawCashNumber = 'FINANCE:WITHDRAW:LIMIT_CASH_NUMBER';// 提现现金次数
    protected $redisKeyWithdrawBankNumber = 'FINANCE:WITHDRAW:LIMIT_BANK_NUMBER';// 提现银行卡张数
    protected $redisKeyWithdrawWeek = 'FINANCE:WITHDRAW:LIMIT_WEEK';// 提现周期
    protected $redisKeyWithdrawExceptionUser = 'FINANCE:WITHDRAW:EXCEPTION_USER';// 提现例外用户

    private $redis_withdraw_token = "finance:withdraw:token";

    //个体工商户
    const ACCOUNT_TYPE_INDIVIDUAL = 1;
    //个人普通账户
    const ACCOUNT_TYPE_PERSONAL = 0;

    //成功打款
    const PAY_STATUS_SUCCESS = 1;

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 支付订单状态修改
     * @param $order_sn
     * @param $out_trade_sn
     * @return int
     */
    public function pay_order($order_sn, $out_trade_sn, $tax_after, $pay_type = 1, $whereStatus = 0, $updateStatus = 1 ,$merchant_no = '', $remark = ''){
        $upData = [
            'pay_type'=> $pay_type, 
            'status' => $updateStatus, 
            'pay_timestamp' => time(), 
            'out_trade_sn' => $out_trade_sn, 
            'tax_after' => $tax_after,
        ];
        if(!empty($merchant_no)){
            $upData['merchant_no'] = $merchant_no;
        }
        if(!empty($remark)){
            $upData['remark'] = $remark;
        }

        $result = DB::table('finance_withdraw_order')
            ->where(['order_sn' => $order_sn, 'status' => $whereStatus])
            ->update($upData);
        return $result;
    }

    /**
     * 支付订单状态修改
     * @param $order_sn
     * @return int
     */
    public function payOrderStatus($order_id, $whereStatus = 0, $updateStatus = 1, $out_order_id, $remark = ''){
        $upData = ['status' => $updateStatus, 'pay_timestamp' => time(), 'out_order_id' => $out_order_id];
        if(!empty($remark)){
            $upData['remark'] = $remark;
        }

        $result = DB::table('finance_withdraw_order')
            ->where(['order_id' => $order_id, 'status' => $whereStatus])
            ->update($upData);
        return $result;
    }

    /**
     * 支付订单修改
     */
    public function withdrawOrderUpdate($order_sn, $data=[], $where=[]){
        $upData = [];
        if(!empty($data['remark'])) {
            $upData['remark'] = $data['remark'];
        }
        if(!empty($data['pay_type'])) {
            $upData['pay_type'] = $data['pay_type'];
        }
        if(empty($upData)){
            return false;
        }

        $whereData = [];
        $whereData['order_sn'] = $order_sn;

        $result = DB::table('finance_withdraw_order')
            ->where($whereData)
            ->update($upData);
        return $result;
    }


    /**
     * 驳回订单状态修改
     * @param $order_sn
     * @return int
     */
    public function dismiss_order($order_sn){
        $result = DB::table('finance_withdraw_order')
            ->where(['order_sn' => $order_sn])
            ->update(['status' => 2, 'dismiss_timestamp' => time(),'update_time'=>time()]);
        return $result;
    }


    /**
     * 获取订单信息
     * @param $order_sn
     * @return mixed|null
     */
    public function get_order($order_sn){
        $result = DB::table('finance_withdraw_order')
            ->where(['order_sn' => $order_sn])
            ->first();
        if (empty($result)){
            return null;
        }
        $data = self::objToArray($result);
        return $data;
    }


    /**
     * 获取当前用户提现总金额
     * @param $user_id
     */
    public function getMonthPrice($user_id){
        $beginThismonth = mktime(0,0,0, date('m'),1, date('Y'));
        $endThismonth = mktime(23,59,59, date('m'), date('t'), date('Y'));
        $result = DB::table('finance_withdraw_order')
            ->where('user_id', '=', $user_id)
            ->where('pay_timestamp', '>=', $beginThismonth)
            ->where('pay_timestamp', '<=', $endThismonth)
            ->where('status', '=', 1)
            ->sum('price');
        if (empty($result)){
            return 0;
        }
        return $result;
    }

    /**获取当前用户提现总金额
     * @param $user_ids
     * @return int|mixed
     */
    public function getMonthPriceByUserIds($user_ids ,$beginThismonth = '',$endThismonth = ''){
        $beginThismonth = empty($beginThismonth) ?  mktime(0,0,0, date('m'),1, date('Y')) : $beginThismonth;
        $endThismonth = empty($endThismonth) ? mktime(23,59,59, date('m'), date('t'), date('Y')) : $endThismonth;
        $result = DB::table('finance_withdraw_order')
            ->whereIn('user_id', $user_ids)
            ->where('create_timestamp', '>=', $beginThismonth)
            ->where('create_timestamp', '<=', $endThismonth)
            ->whereIn('status', array(0,1,3))
            ->sum('price');
        if (empty($result)){
            return 0;
        }
        return $result;
    }

    /**
     * 获取当前用户提现中总金额
     * @param $user_id
     */
    public function getAllPrice($user_id){
        $result = DB::table('finance_withdraw_order')
            ->where('user_id', '=', $user_id)
            ->whereIn('status', [0,3])
            ->sum('price');
        if (empty($result)){
            return 0;
        }
        return $result;
    }

    /**
     * 修改支付类型
     * @param $order_sn
     * @param $payType
     */
    public function changePayType($order_sn, $payType){
        DB::table('finance_withdraw_order')
            ->where(['order_sn' => $order_sn, 'status' => 0])
            ->update(['pay_type' => $payType]);
    }


    public function getDayCount($user_id){
        $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
        $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        $result = DB::table('finance_withdraw_order')
            ->where('user_id', '=', $user_id)
            ->where('create_timestamp', '>=', $beginToday)
            ->where('create_timestamp', '<=', $endToday)
//            ->where('status', '<>', 2)
            ->whereNotIn('status' ,array(2,5))
            ->count();
        if (empty($result)){
            return 0;
        }
        return $result;
    }


    public function getWeekCount($user_id){
        $beginWeek=mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'));
        $endWeek=mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'));
        $result = DB::table('finance_withdraw_order')
            ->where('user_id', '=', $user_id)
            ->where('create_timestamp', '>=', $beginWeek)
            ->where('create_timestamp', '<=', $endWeek)
            ->where('status', '<>', 2)
            ->count();
        if (empty($result)){
            return 0;
        }
        return $result;
    }



    public function set_openid($user_id, $openid){
        Redis::HSET($this->redis_withdraw_token, $user_id, $openid);
        return true;
    }

    public function get_openid($user_id){
        $openid = Redis::HGET($this->redis_withdraw_token, $user_id);
        if (empty($openid)){
            return null;
        }
        return $openid;
    }

    public function queryOrder($data = [], $isSingle = false)
    {
        if ($isSingle) {
            $result = DB::table('finance_withdraw_order')->where($data)->first();
            return self::objToArray($result);
        } else {
            $result = DB::table('finance_withdraw_order')->where($data)->get()->toArray();
            return self::objToArray($result);
        }
    }

    public function applyWithdraw($data){
        $orderId = DB::table('finance_withdraw_order')->insertGetId($data);
        return $orderId;
    }

    // ########## START 提现规则限制 全局设定 ########################################
    /**
     * 提现现金次数
     *
     * @param $number int 次数
     * @param $operateType string 默认读操作 write/read
     *
     * @return bool
     * */
    public function withdrawCashNumber($number=0,$operateType='read'){
        $result = 0;

        switch ($operateType){
            case 'write':
                Redis::set($this->redisKeyWithdrawCashNumber, $number);
                $result = intval($number);
                break;
            case 'read':
                if(Redis::exists($this->redisKeyWithdrawCashNumber)){
                    $result = intval(Redis::get($this->redisKeyWithdrawCashNumber));
                }
                break;
            default:
                break;
        }

        return $result;
    }

    /**
     * 提现银行卡张数
     *
     * @param $number int 张数
     * @param $operateType string 默认读操作 write/read
     *
     * @return bool
     * */
    public function withdrawBankNumber($number=0,$operateType='read'){
        $result = 0;

        switch ($operateType){
            case 'write':
                Redis::set($this->redisKeyWithdrawBankNumber, $number);
                $result = intval($number);
                break;
            case 'read':
                if(Redis::exists($this->redisKeyWithdrawBankNumber)){
                    $result = intval(Redis::get($this->redisKeyWithdrawBankNumber));
                }
                break;
            default:
                break;
        }

        return $result;
    }

    /**
     * 提现周期
     *
     * @param $week array 参数 [0,1,2,3,4,5,6]
     * @param $operateType string 默认读操作 write/read
     *
     * @return array
     * */
    public function withdrawWeek($week=[],$operateType='read'){
        $result = [];

        switch ($operateType){
            case 'write':
                Redis::set($this->redisKeyWithdrawWeek, json_encode($week,JSON_UNESCAPED_UNICODE));
                $result = $week;
                break;
            case 'read':
                if(!Redis::exists($this->redisKeyWithdrawWeek)) {
                    $result = [];
                }else{
                    $result = json_decode(Redis::get($this->redisKeyWithdrawWeek),true);
                }
                break;
            default:
                break;
        }

        return $result;
    }

    /**
     * 提现例外用户
     *
     * @param $data array 参数 ['user_id','nickname','number','operate_nickname','status'] 用户ID 用户昵称 每日提现次数 操作人 状态（0:关闭,1:开启）
     * @param $operateType string  默认读操作 write/read/read_all
     *
     * @return array
     * */
    public function withdrawExceptionUser($data=[],$operateType='read'){
        $result = [];

        switch ($operateType){
            case 'write':
                if(!Redis::hexists($this->redisKeyWithdrawExceptionUser, $data['user_id'])){
                    // 创建日期
                    $data['timestamp'] = time();
                    $data['date'] = date('Y-m-d H:i:s');

                    Redis::hmset($this->redisKeyWithdrawExceptionUser, [$data['user_id'] => json_encode($data,JSON_UNESCAPED_UNICODE)]);
                    $result = $data;
                }else{
                    $retData = json_decode(Redis::hget($this->redisKeyWithdrawExceptionUser, $data['user_id']),true);
                    foreach ($retData as $key => $value){
                        if(array_key_exists($key,$data)){
                            $retData[$key] = $data[$key];
                        }
                    }

                    Redis::hmset($this->redisKeyWithdrawExceptionUser, [$data['user_id'] => json_encode($retData,JSON_UNESCAPED_UNICODE)]);
                    $result = $data;
                }
                break;
            case 'read':
                if(!Redis::hexists($this->redisKeyWithdrawExceptionUser, $data['user_id'])){
                    $result = [];
                }else {
                    $result = json_decode(Redis::hget($this->redisKeyWithdrawExceptionUser, $data['user_id']), true);
                }
                break;
            case 'read_all':
                $resultData = Redis::hgetall($this->redisKeyWithdrawExceptionUser);
                foreach ($resultData as $key => $value) {
                    $result[] = json_decode($value, true);
                }
                break;
            default:
                break;
        }

        return $result;
    }

    /**获取提现记录
     * @param $user_id
     * @param $page
     * @param $limit
     * @return mixed
     */
    public function getWithdrawLog($user_id ,$page ,$limit){
        $res = DB::table('finance_withdraw_order')
            ->where('user_id' ,$user_id)
            ->where('if_hide' ,0)
            ->orderBy('create_timestamp', 'desc')
            ->offset($page * $limit)
            ->limit($limit)
            ->get();
        $res = $this->objToArray($res);
        foreach ($res as &$val){
            $val['price'] = $val['price']/100;
        }
        return $res;
    }

    /**
     * 撤回申请订单状态修改
     * @param $order_sn
     * @return int
     */
    public function recall_order($order_sn){
        $result = DB::table('finance_withdraw_order')
            ->where(['order_sn' => $order_sn])
            ->update(['status' => 5, 'dismiss_timestamp' => time()]);
        return $result;
    }

    /**
     * @param $userId
     * @return bool
     * @desc 获取当前用户是否能提现打款
     */
    public function isAllowWithDraw($userId)
    {
        $accountType = self::ACCOUNT_TYPE_PERSONAL;
        //获取用户当前账户类型
        $cloud = (new FinanceNotifyLog())->getCloudUserByUserId($userId);
        if ($cloud &&  in_array($cloud['status'], [FinanceNotifyLog::CLOUD_LICENSE_SUCCESS, FinanceNotifyLog::CLOUD_LICENSE_TAXATION])) {
            $accountType = self::ACCOUNT_TYPE_INDIVIDUAL;
        }

        $beginM = mktime(0,0,0, date('m'),1,date('Y'));
        $endM = mktime(23,59,59, date('m'),date('t'),date('Y'));
        //个体工商户本月有普通账户类型提现，则不打款，下月打款(添加云账户限制 pay_type=3)
        $order = DB::table('finance_withdraw_order')
            ->where(['user_id' => $userId,  'account_type' => self::ACCOUNT_TYPE_PERSONAL,'pay_type' => 3])
            ->whereIn('status',[0,1,3])
            ->whereBetween('create_timestamp', [$beginM, $endM])
            ->first();

        if (!$accountType && $order) {
            return false;
        }
        return true;
    }

    /**
     * 用户提现账号慧用工删除
     */
    public function financeYuqueDel($userId){
        $result = DB::table($this->financeYuqueTable)
            ->where('user_id', $userId)
            ->where('is_deleted', 0)
            ->update(['is_deleted'=>1, 'deleted_at'=>date("Y-m-d H:i:s", time())]);
        return $result;
    }

    /**
     * 用户提现账号慧用工新增
     */
    public function financeYuqueAdd($data){
        $id = DB::table($this->financeYuqueTable)->insertGetId($data);
        return $id;
    }

    /**
     * 获取用户提现支付宝信息
     */
    public function getUserAlipay($userId, $id){
        $query = DB::table($this->financeYuqueTable)->where('is_deleted', 0)->where('user_id', $userId);
        if(!empty($id)) {
            $query = $query->where('id', $id);
        }
        $res = $query->first();
        $res = $this->objToArray($res);

        return $res;
    }


}
